﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DHQGHN.DAL.BO.Admin;
using DHQGHN.Common;
using DHQGHN.DAL.Common;
using DHQGHN.PM0.Models.Admin;
using DHQGHN.PM0.Controllers;
using DHQGHN.PM0.Common.Attributes;
using DHQGHN.MVC.Controllers;

namespace DHQGHN.PM0.Controllers.Admin
{
    public class CountryController : BaseController
    {
        public const int REQUEST_ACTIVE = 1;
        CountryBO countryBO;
        log4net.ILog logger = log4net.LogManager.GetLogger(typeof(CountryController));
        public ActionResult Index(CountryModel a = null, int pageIndex = 0, string sort = "Id", string sortDir = "ASC", string currentId = null)
        {
            try
            {
                if(a==null)
                    a = new CountryModel();

                if (string.IsNullOrEmpty(currentId))
                    currentId = string.Empty;

                ViewBag.ActiveMenus = ViewBag.ActiveMenus == null ? new System.Collections.Hashtable() : ViewBag.ActiveMenus;
                ViewBag.ActiveMenus[13] = "active";
                ViewBag.ActiveMenus[24] = "active";
                a.Deleted = 2;
                var model = search(a, pageIndex, currentId, false);
                return View("~/Views/Country/Country.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        /// Hiển thị form thêm mới quốc gia
        [HttpPost]

        public ActionResult actionPrepareCreateOrUpdateCountry(string id)
        {
            try
            {
                CountryModel model = null;
                if (!(String.IsNullOrEmpty(id) || String.IsNullOrWhiteSpace(id)))
                {
                    countryBO = new CountryBO();
                    model = new CountryModel(countryBO.GetCountryById(id));
                }
                if (model == null)
                {
                    model = new CountryModel()
                    {
                        Country_ID = string.Empty,
                        Country_Code2 = string.Empty,
                        Country_Code3 = string.Empty,
                        Country_Name = string.Empty,
                        Nationality_Name = string.Empty,
                        Descriptions = string.Empty,
                    };
                }
                if (Request.IsAjaxRequest())
                {
                    return PartialView("~/Views/Country/_CountryModel.cshtml", model);
                }
                return View(model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [HttpPost]
        public ActionResult actionSearch(CountryModel aModel = null, int pageIndex = 0, string sort = "CountryId", string sortDir = "ASC", string currentId = null)
        {
            try
            {
                if (aModel == null) aModel = new CountryModel();

                if (string.IsNullOrEmpty(currentId))
                    currentId = string.Empty;

                var model = search(aModel, pageIndex, currentId, false);
                return PartialView("~/Views/Country/_CountryList.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [AjaxValidateAntiForgeryToken]
        //Define request: Active = 1
        public ActionResult actionActive(string id)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    countryBO = new CountryBO();
                    bool result = countryBO.activeCountry(id, REQUEST_ACTIVE);
                    if (result)
                    {
                        LogStream.Write(GetCurrentUserName(),
                            CommonData.AppName,
                            GetFunction(),
                            CommonData.GetListId(new string[] { id }),
                            Resources.Localization.ActionActiveCaption + " - actionActive");

                        return Json(JsonResponse.Json200("Khôi phục quốc gia thành công!"));
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }

                return null;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        /// Thêm mới quốc gia
        [HttpPost]
        [ValidateInput(false)]
        [AjaxValidateAntiForgeryToken]
        public ActionResult actionCreateOrUpdateCountry(CountryModel model)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    countryBO = new CountryBO();
                    bool result = countryBO.createOrUpdateCountry(model.toDALModel());
                    if (result)
                    {
                        LogStream.Write<CountryModel>(GetCurrentUserName(),
                         CommonData.AppName,
                         GetFunction(),
                         Resources.Localization.ActionSaveUpdateCaption + " - actionCreateOrUpdateCountry", model);

                        if (!(String.IsNullOrEmpty(model.Country_ID) || String.IsNullOrWhiteSpace(model.Country_ID)))
                        {
                            return Json(JsonResponse.Json200("Cập nhật quốc gia thành công!"));
                        }
                        else
                        {
                            return Json(JsonResponse.Json200("Thêm mới quốc gia thành công!"));
                        }
                    }
                    
                    return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                }

                return null;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [AjaxValidateAntiForgeryToken]
        public ActionResult actionDelete(string[] listID)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    countryBO = new CountryBO();
                    bool result = countryBO.deleteCountry(listID);
                    if (result)
                    {
                        LogStream.Write(GetCurrentUserName(),
                            CommonData.AppName,
                            GetFunction(),
                            CommonData.GetListId(listID),
                            Resources.Localization.ActionDeleteCaption + " - actionDelete");
                        return Json(JsonResponse.Json200("Xóa quốc gia thành công!"));
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }

                return null;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private DataPage<CountryModel> search(CountryModel myModel, int pageIndex, string currentId, bool compareEqual)
        {
            try
            {
                countryBO = new CountryBO();

                var DALModel = countryBO.GetDynamicListPaging(myModel.toDALModel(), PageSize, pageIndex, compareEqual);
                var models = new DataPage<CountryModel>();
                var lstItem = DALModel.Data;
                foreach (DHQGHN.DAL.Models.Admin.CountryModel country in lstItem)
                {
                    models.Data.Add(new CountryModel(country));
                }

                CountryModel model = null;
                if (!String.IsNullOrEmpty(currentId) && models.Data.Count > 0)
                {
                    model = models.Data.Find(user => user.Country_ID.Equals(currentId));
                    models.CustomData = model;
                }
                else
                {
                    models.CustomData = myModel;
                }
                if (models.Data.Count > 0)
                {
                    //Tao component phan trang
                    var pagNative = new Pagination
                    {
                        ActionName = "actionSearch",
                        ModelName = "Country",
                        CurrentPage = pageIndex,
                        InputSearchId = string.Empty,
                        TagetReLoadId = "country-list",

                    };
                    pagNative.TotalRows = models.Data[0].RecordCount;
                    pagNative.CurrentRow = models.Data.Count;
                    ViewBag.Pagination = pagNative;
                }
                return models;
            }
            catch
            {
                throw;
            }
        }

        //Kiểm tra tên quốc gia đã tồn tại chưa
        public JsonResult CheckExistCountryName(string Country_Name, string Country_ID)
        {
            try
            {
                CountryModel countryModel = new CountryModel()
                {
                    Country_Name = Country_Name.Trim(),
                    Deleted = 2
                };

                if (IsExistValuesOfModel(countryModel, Country_ID))
                {
                    return Json(Resources.Localization.CountryNameExist);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        //Kiểm tra mã quốc gia đã tồn tại chưa
        public JsonResult CheckExistCountryCode2(string Country_Code2, string Country_ID)
        {
            try
            {
                CountryModel countryModel = new CountryModel()
                {
                    Country_Code2 = Country_Code2.Trim(),
                    Deleted = 2,
                };
                if (IsExistValuesOfModel(countryModel, Country_ID))
                {
                    return Json(Resources.Localization.CountryCodeExist);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        //Kiểm tra mã quốc gia đã tồn tại chưa
        public JsonResult CheckExistCountryCode3(string Country_Code3, string Country_ID)
        {
            try
            {
                CountryModel countryModel = new CountryModel()
                {
                    Country_Code3 = Country_Code3.Trim(),
                    Deleted = 2,
                };
                if (IsExistValuesOfModel(countryModel, Country_ID))
                {
                    return Json(Resources.Localization.CountryCodeExist);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        //Kiểm tra mã quốc gia đã tồn tại chưa
        public JsonResult CheckExistCountryNumericCode(int Numeric_Code, string Country_ID)
        {
            try
            {
                CountryModel countryModel = new CountryModel()
                {
                    Numeric_Code = Numeric_Code,
                };
                if (IsExistValuesOfModel(countryModel, Country_ID))
                {
                    return Json(Resources.Localization.CountryCodeExist);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }


        public bool IsExistValuesOfModel(CountryModel countryModel, string Country_ID)
        {
            try
            {
                var model = search(countryModel, 0, string.Empty, true);
                if (model.Data.Any())
                {
                    var lstItem = model.Data;
                    foreach (CountryModel country in lstItem)
                    {
                        if (!(String.IsNullOrWhiteSpace(Country_ID) || String.IsNullOrEmpty(Country_ID)))
                        {
                            if (!(country.Country_ID.Equals(Country_ID)))
                            {
                                return true;
                            }
                        }
                        else
                        {
                            //Kiem tra truong hop them moi
                            return true;
                        }
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private string GetFunction()
        {
            return "Danh mục quốc gia - CountryController";
        }
    }
}